package org.jmetrix.throughput;

import org.aspectj.lang.ProceedingJoinPoint;
import org.jmetrix.bus.Bus;
import org.jmetrix.bus.impl.NamedBusFactory;
import org.jmetrix.group.GroupAspect;

import java.util.concurrent.TimeUnit;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 05.09.12
 */
public class ThroughputAspect extends GroupAspect {
    private Bus bus;

    protected ThroughputAspect() {
        bus = NamedBusFactory.getDefaultBus();
    }

    protected Bus getBus() {
        return bus;
    }

    protected TimeUnit getTimeUnit() {
        return TimeUnit.SECONDS;
    }

    @Override
    protected String getGroup(ProceedingJoinPoint pjp) {
        return getName(pjp);
    }

    protected Object proceed(ProceedingJoinPoint pjp) throws Throwable {
        try {
            return pjp.proceed();
        } finally {
            getBus().publish(new ThroughputEvent(getName(pjp), getTimeUnit()));
        }
    }

    protected String getName(ProceedingJoinPoint pjp) {
        return pjp.getTarget().getClass().getCanonicalName() + "." + pjp.getSignature().getName();
    }
}
